<template>
  <div class="login-container">
    <el-card class="login-card">
      <div class="logo-container">
        <img src="@/assets/logo.svg" alt="Logo" class="logo">
      </div>
      <h2 class="login-title">IoT 系统注册</h2>
      <el-form ref="registerForm" :model="registerData" :rules="registerRules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="registerData.username" placeholder="请输入用户名" autocomplete="off" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="registerData.password" type="password" placeholder="请输入密码" autocomplete="off" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="registerData.confirmPassword" type="password" placeholder="请确认密码" autocomplete="off" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="registerData.nickname" placeholder="请输入昵称" autocomplete="off" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="registerData.phone" placeholder="请输入手机号" autocomplete="off" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="registerData.email" placeholder="请输入邮箱" autocomplete="off" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleRegister" class="login-btn">注册</el-button>
          <el-button @click="resetForm" class="reset-btn">重置</el-button>
        </el-form-item>
        <el-divider />
        <div class="login-link">
          <span>已有账号？</span>
          <el-button type="text" @click="router.push('/login')">立即登录</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const router = useRouter()

// 注册表单数据
const registerData = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  nickname: '',
  phone: '',
  email: ''
})

// 表单引用
const registerForm = ref(null)

// 注册表单验证规则
const registerRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, message: '用户名长度不能少于3位', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: (rule, value, callback) => {
        if (value !== registerData.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      }, trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ]
})

// 处理注册
const handleRegister = async () => {
  // 验证表单
  await registerForm.value.validate().catch(() => {
    return
  })

  try {
    // 准备请求数据
    const requestData = {
      username: registerData.username,
      password: registerData.password,
      nickname: registerData.nickname,
      phone: registerData.phone,
      email: registerData.email
    }

    const res = await axios.post('/register', requestData, {
      headers: {
        'Content-Type': 'application/json'
      }
    })

    if (res.data.code === 200) {
      ElMessage.success('注册成功，请登录！')
      // 跳转到登录页
      router.push('/')
    } else {
      ElMessage.error(res.data.msg || '注册失败')
    }
  } catch (err) {
    console.error('注册错误:', err)
    // 处理后端返回的重复注册错误
    if (err.response?.status === 409 || err.response?.data?.msg?.includes('重复') || err.response?.data?.msg?.includes('存在')) {
      ElMessage.error('用户名或邮箱已被使用')
    } else {
      ElMessage.error('注册失败，请检查网络连接或稍后重试')
    }
  }
}

// 重置表单
const resetForm = () => {
  registerForm.value.resetFields()
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.login-card {
  width: 420px;
  padding: 40px 30px;
  border-radius: 20px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
}

.logo-container {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.logo {
  width: 80px;
  height: 80px;
  object-fit: contain;
}

.login-title {
  text-align: center;
  margin-bottom: 30px;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.el-form-item {
  margin-bottom: 25px;
}

.el-input__wrapper {
  border-radius: 20px;
  padding: 10px 15px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
}

.el-input__wrapper:focus-within {
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
}

.login-btn, .reset-btn {
  width: 100%;
  margin-top: 15px;
  border-radius: 20px;
  padding: 12px;
  font-size: 16px;
  transition: all 0.3s ease;
}

.login-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
}

.login-btn:hover {
  background: linear-gradient(135deg, #5568d3 0%, #653a8b 100%);
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.4);
}

.reset-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
}

.login-link {
  text-align: center;
  color: #606266;
  font-size: 14px;
}

.login-link span {
  margin-right: 10px;
}
</style>